import { createRouter, createWebHistory, type RouteRecordRaw } from "vue-router";
import Layout from '@/layout/Index.vue'
import { useUserStore } from '@/store/user'
import { useMenuStore } from '@/store/menu'

// 动态路由 - 保持你原有的路由结构
export const constantRoutes: Array<RouteRecordRaw> = [
    {
        path: '/login',
        component: () => import('@/views/login/Login.vue'),
        name: '/login',
    },
    {
        path: '/',
        component: Layout,
        redirect: '/dashboard',
        children: [
            {
                path: '/dashboard',
                component: () => import('@/views/dashboard/Dashboard.vue'),
                name: 'dashboard',
                meta: {
                    title: '看板',
                    icon: '#icondashboard'
                }
            }
        ]
    },
    // 可选：如果你有 404 页面就取消注释
    {
        path: '/:pathMatch(.*)*',
        name: 'NotFound',
        component: () => import('@/views/404.vue')
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes: constantRoutes
})

// 🟢 新增：路由守卫
router.beforeEach(async (to, from, next) => {
    const userStore = useUserStore()
    const menuStore = useMenuStore()

    // 白名单
    if (to.path === '/login') {
        next()
        return
    }

    // 检查登录
    if (!userStore.userId) {
        next('/login')
        return
    }

    // 初始化路由
    if (!menuStore.isRoutesInitialized) {
        try {
            console.log('开始初始化动态路由...')
            await menuStore.getMenuList(router, userStore.userId)
            console.log('动态路由初始化完成')
            next(to.fullPath)
            return
        } catch (error) {
            console.error('路由初始化失败:', error)
            next('/login')
            return
        }
    }

    next()
})

export default router